using Godot;
using System;

public partial class EquipItemSlot : MarginContainer
{
	[Signal]
	public delegate void ItmeSlotSelctedEventHandler(Item item);
	[Signal]
	public delegate void DropToEquipmentEventHandler( string to,Item item);
	private UiInventory _inventory;
	private ItemTile item_tile;
	public Item _item;
	private bool selectable;
	public Item item
	{
		get{ return _item; }
		set{
			item_setter(value);
		}
	}
	public void item_setter(Item value)
	{
		_item = value;
		if (value != null)
		{
			item_tile.update_display(value);
			item_tile.Show();
		}
		else
		{
			item_tile.Hide();
		}
	}
	// Called when the node enters the scene tree for the first time.
	public void Initialize()
    {
        item_tile = (ItemTile)GetChild(0).GetChild(0);
		this.MouseEntered += () => selectable = true;
		this.MouseExited += () => selectable = false;
		var UIControl = GetNode<UIControl>("/root/UIControl");
		_inventory = UIControl.GetGuiViewManager().GetNode<UiInventory>("%UiInventory");
    }

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public override void _Input(InputEvent @event)
	{
		if (@event is InputEventMouseButton mouseEvent&&selectable)
		{
			GD.Print("mouse button event at ", mouseEvent.Position,this.Name);
			EmitSignal(SignalName.ItmeSlotSelcted,item);
		}
	}

	public override Variant _GetDragData(Vector2 atPosition)
	{
		if(item == null)
		{return false;}
		GD.Print("正在拖拽");
		TextureRect preview = new TextureRect();
		preview.Texture = item_tile._textureRect.Texture;
		preview.Scale = item_tile._textureRect.Scale;
		preview.Visible = true;
		SetDragPreview(preview);
		_inventory.DropSource = this.Name;
		return item;
	}

	public override bool _CanDropData(Vector2 atPosition, Variant data)
    {
		if(item==null&&(_inventory.DropSource!=this.Name))
		{return true;}
		return false;
    }
	public override void _DropData(Vector2 atPosition, Variant data)
	{
		Item changeitem = (Item)data;
		//GD.Print(changeitem.name);
		EmitSignal(SignalName.DropToEquipment,this.Name,changeitem);
		
	}
}
